// store/index.js
import { createStore } from 'vuex';
import axios from 'axios';

export default createStore({
  state() {
    return {
      user: { // 初始化为一个空对象
        username: '',
        password: '',
      }
    };
  },
  mutations: {
    setUser(state, user) {
      state.user = user;
    }
  },
  actions: {
    login({ commit }, credentials) {
      return new Promise((resolve, reject) => {
        axios.post('http://localhost:8080/user/login', {
          username: credentials.username,
          password: credentials.password,
          // 其他参数...
        })
            .then((response) => {
              if (response.data.msg === 'success') {
                // 确保 response.data.data 是一个对象
                const user = response.data.data;
                commit('setUser', user);
                alert('登录成功！');
                resolve(user);
              } else {
                alert('登录失败: ' + response.data.msg);
                reject(response.data.msg);
              }
            })
            .catch((error) => {
              if (error.response && error.response.data) {
                // 这里处理了后端返回的具体错误信息
                alert('登录请求出错：' + error.response.data.msg);
              } else {
                // 这里处理了其他类型的错误（如网络错误等）
                alert('登录请求出错，请稍后重试。');
              }
              console.error('登录请求出错', error);
              reject(error);
            });
      });
    }
  },
  getters: {
    isLoggedIn: (state) => !!state.user, // 用户是否已登录
    isPremiumUser: (state) => {
      if (!state.user) return false; // 如果 user 为 null，直接返回 false
      return state.user.isPremium;
    },
    username: (state) => state.user?.username, // 获取用户名
    password: (state) => state.user?.password, // 获取密码
  }
});
